package com.plugin.storage.base;

import com.google.common.base.Strings;
import com.google.common.collect.Streams;
import com.plugin.storage.storage.spi.UploadProvider;
import com.plugin.storage.storage.spi.VideoProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.ServiceLoader;

public abstract class SdkClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(SdkClient.class);

    protected List<SdkContext> contexts;

    public List<SdkContext> getContexts() {
        return contexts;
    }

    public SdkClient setContexts(List<SdkContext> contexts) {
        this.contexts = contexts;
        return this;
    }

    protected UploadProvider getUploadProvider() {
        ServiceLoader<UploadProvider> serviceLoader = ServiceLoader.load(UploadProvider.class);
        return Streams.stream(serviceLoader.iterator()).findAny().orElseThrow(() -> new StorageException("service provider not found."));
    }

    protected VideoProvider getVideoProvider() {
        ServiceLoader<VideoProvider> serviceLoader = ServiceLoader.load(VideoProvider.class);
        return Streams.stream(serviceLoader.iterator()).findAny().orElseThrow(() -> new StorageException("service provider not found."));
    }

    protected SdkContext getContext() {
        return getContext(null);
    }

    protected SdkContext getContext(String bucket) {
        SdkContext context;
        if (contexts.size() == 1) {
            context = contexts.get(0);
        } else if (Strings.isNullOrEmpty(bucket)) {
            context = contexts.stream().filter(e -> !Strings.isNullOrEmpty(e.getBucket())).findAny().orElseThrow(() -> new StorageException("sdk context not found."));
        } else {
            context = contexts.stream().filter(e -> bucket.equals(e.getBucket())).findAny().orElseThrow(() -> new StorageException("sdk context not found."));
        }
        if (!Strings.isNullOrEmpty(bucket)) {
            context = context.clone().setBucket(bucket);
        }
        return context;
    }

    protected SdkContext getContextByEndPoint(String accessEndPoint) {
        SdkContext context;
        if (contexts.size() == 1) {
            context = contexts.get(0);
        } else {
            context = contexts.stream().filter(e -> accessEndPoint.equals(e.getAccessEndpoint())).findAny().orElseThrow(() -> new StorageException("sdk context not found."));
        }
        return context;
    }

}
